package cn.jinjimi.app.main.activity;

import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.UploadProfileEvent;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by haner on 15-1-30.
 */
public class ModifyQQNumActivity extends ToolBarCommonActivity {

    public static final int TYPE_QQ = 1;
    public static final int TYPE_WEIXIN = 2;

    private EditText qq;
    private RelativeLayout cleanQQ;
    private TextView rule;

    int mType = 1;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_modify_qqnum);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
    }

    protected void initView() {
        mType = getIntent().getIntExtra("type", 1);
        qq = (EditText) findViewById(R.id.et_qq);
        cleanQQ = (RelativeLayout) findViewById(R.id.clean_qq);
        setRightText(R.string.save);
        rule = (TextView) findViewById(R.id.input_content_rules_info);
        rule.setVisibility(View.GONE);
        setDataByType();

        //光标移到句末
        Editable etext = qq.getText();
        Selection.setSelection(etext, etext.length());
    }

    private void setDataByType() {
        switch (mType) {
            case TYPE_QQ:
                setTitle(getString(R.string.info_qq));
                qq.setHint(getString(R.string.info_input_qq));
                qq.setText(AccountManager.getInstance().getAccount().qq);
                qq.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                break;
            case TYPE_WEIXIN:
                setTitle(getString(R.string.info_weixin));
                qq.setHint(getString(R.string.info_input_wecht));
                qq.setText(AccountManager.getInstance().getAccount().weixin);
                rule.setVisibility(View.VISIBLE);
                break;
        }
    }

    protected void initListener() {
        cleanQQ.setOnClickListener(this);
        qq.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    cleanQQ.setVisibility(View.VISIBLE);
                } else {
                    cleanQQ.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mType == TYPE_WEIXIN) {//确保输入的微信号首字符为字母数字
                    if (s != null && s.length() > 0) {
                        Pattern p = Pattern.compile("^[0-9a-zA-Z].?");
                        Matcher m = p.matcher(s.toString());
                        if (!m.find()) {
                            s.replace(0, 1, "");
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.clean_qq:
                qq.setText("");
                break;
        }
    }

    @Override
    protected void rightAction() {
        super.rightAction();
        updateInfo();
    }

    private void updateInfo() {
        switch (mType) {
            case TYPE_QQ:
                saveQQ();
                break;

            case TYPE_WEIXIN:
                saveWeixin();
                break;
        }
    }

    private void saveQQ() {
        if (checkQQNum()) {
            if (qq.getText().toString().equals(AccountManager.getInstance().getAccount().qq)) {
                ToastUtils.toastMessage(ModifyQQNumActivity.this, getString(R.string.modify_success));
                finish();
            } else {
                showLoadingIndicator();
                UserController.setQQ(qq.getText().toString().trim(), TYPE_QQ);
            }
        }
    }

    private boolean checkQQNum() {
        if (qq.getText().length() < 5 || qq.getText().length() > 13) {
            ToastUtils.toastMessage(this, getString(R.string.info_qq_limit));
            return false;
        }
        return true;
    }


    private void saveWeixin() {
        if (checkWeixinNum()) {
            if (qq.getText().toString().equals(AccountManager.getInstance().getAccount().weixin)) {
                ToastUtils.toastMessage(ModifyQQNumActivity.this, getString(R.string.modify_success));
                finish();
            } else {
                showLoadingIndicator();
                UserController.setWeixin(qq.getText().toString().trim(), TYPE_WEIXIN);
            }
        }
    }

    private boolean checkWeixinNum() {
        if (qq.getText().length() < 6 || qq.getText().length() > 20) {
            ToastUtils.toastMessage(this, getString(R.string.info_wecht_error));
            return false;
        }
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadProfileEvent(UploadProfileEvent event) {
        if (isFinishing())
            return;
        switch (event.state) {
            case DataEvent.SUCC:
                ToastUtils.toastMessage(ModifyQQNumActivity.this, getString(R.string.modify_success));
                if (event.position == TYPE_QQ) {
                    //此处保存QQ号码
                    AccountManager.getInstance().updateAccount(AccountManager.NameKey.QQ, qq.getText().toString().trim());
                } else if (event.position == TYPE_WEIXIN) {
                    AccountManager.getInstance().updateAccount(AccountManager.NameKey.WEIXIN, qq.getText().toString().trim());
                }
                finish();
                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(ModifyQQNumActivity.this, getString(R.string.modify_fail));
                break;
        }
        hideLoadingIndicator();
    }

}
